package com.yunzai.secure.filter;

import com.alibaba.fastjson2.JSONObject;
import com.yunzai.generic.domain.JSONResult;
import com.yunzai.secure.service.ITokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

@Component
public class TokenFilter extends OncePerRequestFilter {

    @Value("${token.authorization}")
    private String authorization;

    @Autowired
    private ITokenService tokenService;

    /**
     * @param request
     * @param response
     * @param filterChain
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        Object attribute = request.getHeader(authorization);
        if (attribute != null) {
            String token = attribute.toString().substring("Bearer ".length(), attribute.toString().length() - 1);
            Authentication authentication = tokenService.getAuthentication(token);
            SecurityContextHolder.getContext().setAuthentication(authentication);
        }
        filterChain.doFilter(request, response);
    }
}
